<?php

Yii::import('gii.generators.model.ModelCode');

class Model80Code extends ModelCode {

	protected $_excludedColumns = array(
		'createdAt',
		'createdBy',
		'updatedAt',
		'updatedBy'
	);

	public function generateRules($table) {
		$rules = array();
		$required = array();
		$integers = array();
		$numerical = array();
		$length = array();
		$safe = array();
		foreach ($table->columns as $column) {
			if ($column->autoIncrement || in_array($column->name, $this->_excludedColumns))
				continue;
			$r = !$column->allowNull && $column->defaultValue === null;
			if ($r)
				$required[] = $column->name;
			if ($column->type === 'integer')
				$integers[] = $column->name;
			else if ($column->type === 'double')
				$numerical[] = $column->name;
			else if ($column->type === 'string' && $column->size > 0)
				$length[$column->size][] = $column->name;
			else if (!$column->isPrimaryKey && !$r)
				$safe[] = $column->name;
		}
		if ($required !== array())
			$rules[] = "array(\n\t\t\tarray(\n\t\t\t\t'" . implode("',\n\t\t\t\t'", $required) . "',\n\t\t\t),\n\t\t\t'required',\n\t\t\t'on'=>'insert, update',\n\t\t)";
		if ($integers !== array())
			$rules[] = "array(\n\t\t\tarray(\n\t\t\t\t'" . implode("',\n\t\t\t\t'", $integers) . "',\n\t\t\t),\n\t\t\t'numerical',\n\t\t\t'integerOnly'=>true,\n\t\t)";
		if ($numerical !== array())
			$rules[] = "array(\n\t\t\tarray(\n\t\t\t\t'" . implode("',\n\t\t\t\t'", $numerical) . "',\n\t\t\t),\n\t\t\t'numerical',\n\t\t)";
		if ($length !== array()) {
			foreach ($length as $len=> $cols)
				$rules[] = "array(\n\t\t\tarray(\n\t\t\t\t'" . implode("',\n\t\t\t\t'", $cols) . "',\n\t\t\t),\n\t\t\t'length',\n\t\t\t'max'=>$len,\n\t\t)";
		}
		if ($safe !== array())
			$rules[] = "array(\n\t\t\tarray(\n\t\t\t\t'" . implode("',\n\t\t\t\t'", $safe) . "',\n\t\t\t),\n\t\t\t'safe',\n\t\t)";

		return $rules;
	}

}
